package com.youyunsoft.commons.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import androidx.core.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.blankj.utilcode.util.ToastUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.WINDOW_SERVICE;

/**
 * Created by actlistener on 2016/11/17.
 */

public enum Util {
    INSTANCE;
    private Context mContext;
    private Handler mHandler;

    public void init(Context context) {
        mContext = context;
        mHandler = new Handler(Looper.getMainLooper());
    }


//    public void toast(String content) {
//        if (TextUtils.isEmpty(content)) {
//            return;
//        } else {
//            ToastMgr.builder.show(content, Toast.LENGTH_SHORT);
//        }
//    }


    public String getCurrentDate() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(new Date());
        //test
//        date="2017-11-22";

        return date;
    }

    public void toast(String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        ToastUtils.showLong(content);
    }

    public void startActivity(Activity activity, Class clazz) {
        Intent intent = new Intent(mContext, clazz);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }


    public void startActivity(Intent intent) {
        mContext.startActivity(intent);
    }

    public void measureView(View v) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
    }


    public void startActivityForResult(Activity activity, Intent intent, int requestCode) {
        activity.startActivityForResult(intent, requestCode);
    }

    public void startActivityForResult(Activity activity, Class clazz, int requestCode) {
        Intent intent = new Intent(activity, clazz);
        activity.startActivityForResult(intent, requestCode);

    }


    public void startActivity(Activity activity, Intent intent) {
        activity.startActivity(intent);
    }


    public int dp2px(Context context, int dp) {

        float s = context.getResources().getDisplayMetrics().density;
        return (int) (dp * s + 0.5f);
    }

    public int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 判断网络是否有网络
     */
    public boolean isNetWorkAvaliable() {
        if (mContext == null) {
            toast("参数异常");
            return false;
        }
        ConnectivityManager conManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
        return networkInfo == null ? false : networkInfo.isAvailable();
    }


    //隐藏软键盘
    public void hideSoftInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView()
                    .getWindowToken(), 0);
        }
    }

    //弹出软键盘
    public void showSoftInput(View v) {
        InputMethodManager inputManager = (InputMethodManager) v
                .getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(v, 0);
    }

    // 验证手机号
    public boolean isMobileNO(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    public BigDecimal formatDecimalMumber(BigDecimal bigDecimal, int decimalLength) {
        BigDecimal big = null;

        if (bigDecimal != null) {
            big = bigDecimal.setScale(decimalLength, BigDecimal.ROUND_HALF_UP);
        }

        try {
//            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            DecimalFormat df = new DecimalFormat("#0.00");
            big = new BigDecimal(df.format(big));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return big;
    }


    public BigDecimal formatDecimalMumberWithZero(BigDecimal bigDecimal, int decimalLength) {
        BigDecimal big = null;
        if (bigDecimal != null) {
            big = bigDecimal.setScale(decimalLength, BigDecimal.ROUND_HALF_UP);
        }

        return big;
    }


    public BigDecimal formatDecimalMumberWithPoint(BigDecimal bigDecimal, int decimalLength) {
        BigDecimal big = null;

        if (bigDecimal != null) {
            big = bigDecimal.setScale(decimalLength, BigDecimal.ROUND_HALF_UP);
        }

        return big;
    }


//    public Dialog getProgressDialog(Activity activity) {
//        Dialog dialog = null;
//        dialog = new Dialog(activity, R.style.progress_dialog);
//        View dialogContent = View.inflate(activity, R.layout.dialog, null);
//        dialog.addContentView(dialogContent,
//                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//        return dialog;
//    }

    public Point getScreenInfo(Activity activity) {
        Point point = new Point();

        //第一种途径
        Display display = ((WindowManager) mContext.getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        display.getSize(point);
        if (point.x == 0 || point.y == 0) {//第二种途径
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            int height = dm.heightPixels;
            int width = dm.widthPixels;
            point.set(width, height);
        }
        return point;
    }

    public void makePhoneCall(Activity activity, String number) {
        if (TextUtils.isEmpty(number)) {
            return;
        }
        Intent intentPhone = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
        intentPhone.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(activity, intentPhone);
    }


    public String getDeviceID() {

        String defalut = "yydeviceid";

        try {
            WifiManager wifi = (WifiManager) mContext
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String mac = info.getMacAddress();
            if (mac != null && mac.length() > 0) {
                return mac;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            TelephonyManager telephonyManager = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return "";
            }else{
                String IMEI = telephonyManager.getDeviceId();
                if (IMEI != null && IMEI.length() > 0) {
                    return IMEI;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            TelephonyManager telephonyManager = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String sn = telephonyManager.getSimSerialNumber();
            if (sn != null && sn.length() > 0) {
                return sn;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            String devId = "35" + Build.BOARD.length() % 10
                    + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
                    + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10
                    + Build.HOST.length() % 10 + Build.ID.length() % 10
                    + Build.MANUFACTURER.length() % 10 + Build.MODEL.length()
                    % 10 + Build.PRODUCT.length() % 10 + Build.TAGS.length()
                    % 10 + Build.TYPE.length() % 10 + Build.USER.length() % 10; // 13
            // digits

            if (devId.length() > 0) {
                return devId;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            SharedPreferences sPreferences = mContext.getSharedPreferences(
                    "installinfo", Activity.MODE_PRIVATE);
            if (sPreferences.contains("installid")) {
                return sPreferences.getString("installid", defalut);
            } else {
                String uuid = UUID.randomUUID().toString();
                sPreferences.edit().putString("installid", uuid);
                sPreferences.edit().commit();
                return uuid;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defalut;
    }


//    public void ExitApp(Activity activity) {
//
//        Intent intent = new Intent(activity, MainTabActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra(IntentActivity.KEY_INTENT, IntentActivity.INTENT_EXIT_APP);
//        activity.startActivity(intent);
//    }


//    public void loadImg(ImageView view, String url) {
//        try {
//            Picasso.with(mContext).load(url).noFade().error(R.mipmap.img_error).placeholder(R.mipmap.ic_place_holder).into(view);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    public void loadImage(ImageView view, int resId) {
//        try {
//            Picasso.with(mContext).load(resId).noFade().error(R.mipmap.img_error).placeholder(R.mipmap.ic_place_holder).into(view);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    public void loadImg(ImageView imageView, @DrawableRes int resourceId) {
//
//        if (null == imageView) {
//            return;
//        }
//        try {
//            Picasso.get()
//                    .load(resourceId)
//                    .noFade()
//                    .config(Bitmap.Config.RGB_565)
//                    .error(R.mipmap.img_error)
//                    .placeholder(R.mipmap.ic_place_holder)
//                    .into(imageView);
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        }
//
//
//    }

//    public void loadImg(ImageView imageView, String imgUrl) {
//
//        if (null == imageView || TextUtils.isEmpty(imgUrl)) {
//            return;
//        }
//        Picasso.get()
//                .load(imgUrl)
//                .noFade()
//                .config(Bitmap.Config.RGB_565)
//                .error(R.mipmap.img_error)
//                .placeholder(R.mipmap.ic_place_holder)
//                .into(imageView);
//
//
//    }


//    public Point displayImageWithTransform(final Context context, String url, ImageView view, final int width) {
//        final Point point = new Point();
//        if (TextUtils.isEmpty(url)) {
//            Picasso.get().load(R.mipmap.img_error).noFade().config(Bitmap.Config.RGB_565).into(view);
//        } else {
//            Transformation transformation = new Transformation() {
//                @Override
//                public Bitmap transform(Bitmap source) {
//
//                    int height = width * source.getHeight() / source.getWidth();
//
//                    point.x = width;
//                    point.y = height;
//
//                    Bitmap result = Bitmap.createScaledBitmap(source, width, height, false);
//                    if (result != source) {
//                        // Same bitmap is returned if sizes are the same
//                        source.recycle();
//                    }
//                    return result;
//                }
//
//                @Override
//                public String key() {
//                    return "transformation" + " desiredWidth";
//                }
//            };
//
//            //noFade()去掉过度渐变，加载完成替换R.drawable.empty_photo时，如果有渐变，R.drawable.empty_photo替换成实际图片会有一个渐变拉伸过程
//            Picasso.get().load(url).error(R.mipmap.img_error)
//                    .placeholder(R.mipmap.ic_place_holder).noFade().transform(transformation).
//                    config(Bitmap.Config.RGB_565).into(view);
//        }
//        return point;
//    }


    public SpannableString getColoredSpannableString(String text, int start, int end, int color) {
        SpannableString spannableString = null;
        try {
            spannableString = new SpannableString(text);
            spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            spannableString = new SpannableString(text);
        }

        return spannableString;
    }

    public SpannableString getColoredSpannableString(SpannableString spannableString, int start, int end, int color) {
        try {
            spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return spannableString;
    }


    public SpannableString getResizedSpannableString(SpannableString spannableString, int start, int end, int spSize) {
        try {
            int size = px2dp(mContext, sp2px(mContext, spSize));
            spannableString.setSpan(new AbsoluteSizeSpan(size, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return spannableString;
    }

    public SpannableString getResizedSpannableString(String text, int start, int end, int spSize) {

        SpannableString spannableString = null;

        try {
            spannableString = new SpannableString(text);
            int size = px2dp(mContext, sp2px(mContext, spSize));
            spannableString.setSpan(new AbsoluteSizeSpan(size, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        } catch (Exception e) {
            spannableString = new SpannableString(text);
        }

        return spannableString;
    }

}
